package controller

import (
	"bytes"
	"encoding/json"
	bc "fabric-test3/application/blockchain"
	"fabric-test3/application/lib"
	"fabric-test3/application/util"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

//  创建一个新的交易
func NewTransaction(ctx *gin.Context) {
	req := new(lib.Transaction)
	if err := ctx.ShouldBind(req); err != nil {
		_ = ctx.AbortWithError(http.StatusBadRequest, err)
	}
	req.Id = util.Krand(11, 0)
	marshal, _ := json.Marshal(req)
	resp, err := bc.ChannelExecute("newTransaction", [][]byte{
		marshal,
	})
	if err != nil {
		fmt.Println("ERROR: ", err.Error())
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}
	ctx.JSON(http.StatusOK, resp)
}

//  确认订单
func ConfirmTransaction(ctx *gin.Context) {

}

//  支付订单
func PayTransaction(ctx *gin.Context) {

}

//  改成发货状态
func UpdateShipmentInfo(ctx *gin.Context) {

}

//  改成发货状态
func RepayTransaction(ctx *gin.Context) {

}

//获取交易信息
func GetTransactions(ctx *gin.Context) {
	keysStr := ctx.Query("keys")
	keysBytes := []byte("[]")
	if keysStr != "" {
		keys := strings.Split(keysStr, ",")
		marshal, err := json.Marshal(keys)
		if err != nil {
			ctx.String(http.StatusInternalServerError, err.Error())
			return
		}
		keysBytes = marshal
	}
	resp, err := bc.ChannelQuery("getTransactions", [][]byte{
		keysBytes,
	})
	if err != nil {
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}

	// 将结果返回
	ctx.String(http.StatusOK, bytes.NewBuffer(resp.Payload).String())
}

//获取交易信息
func GetTransactionHistory(ctx *gin.Context) {
	var key string
	key = ctx.Query("key")
	if key == "" {
		ctx.String(http.StatusInternalServerError, "missing parameters")
		return
	}
	resp, err := bc.ChannelQuery("getTransactionHistory", [][]byte{
		[]byte(key),
	})
	if err != nil {
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}

	// 将结果返回
	ctx.String(http.StatusOK, bytes.NewBuffer(resp.Payload).String())
}
